/**
 * Electron 历史解析器适配器
 * 使用 Electron API 替代直接的 Node.js 文件系统调用
 */

import type { HistoryVersion, FileHistoryRecord } from '../types/basic'
import { ErrorType, type AppError } from '../types/errors'



export class ElectronHistoryParserImpl {
  /**
   * 扫描历史版本目录
   */
  async scanHistoryVersions(historyPath: string): Promise<HistoryVersion[]> {
    try {
      const resolvedPath = window.pathAPI.resolve(historyPath)
      const result = await window.electronAPI.readDirectory(resolvedPath)
      
      if (!result.success) {
        throw new Error(result.error || 'Failed to read directory')
      }
      
      const versions: HistoryVersion[] = []
      
      for (const file of result.files || []) {
        if (file.isDirectory) {
          try {
            const hasEntriesFile = await this.checkEntriesFile(file.path)
            const fileCount = await this.countFiles(file.path)
            
            versions.push({
              id: file.name,
              timestamp: file.mtime ? file.mtime.getTime() : Date.now(),
              fileCount,
              hasEntriesFile
            })
          } catch (error) {
            console.warn(`Failed to parse version directory ${file.path}:`, error)
          }
        }
      }
      
      // 按时间戳排序（最新的在前）
      return versions.sort((a, b) => b.timestamp - a.timestamp)
    } catch (error) {
      throw this.createError(
        ErrorType.FILE_NOT_FOUND,
        `Failed to scan history versions: ${error instanceof Error ? error.message : String(error)}`
      )
    }
  }

  /**
   * 检查版本目录是否有 entries 文件
   */
  private async checkEntriesFile(versionPath: string): Promise<boolean> {
    try {
      const entriesPath = window.pathAPI.join(versionPath, 'entries')
      const result = await window.electronAPI.readFile(entriesPath)
      return result.success
    } catch {
      return false
    }
  }

  /**
   * 统计版本目录中的文件数量
   */
  private async countFiles(versionPath: string): Promise<number> {
    try {
      const result = await window.electronAPI.readDirectory(versionPath)
      
      if (!result.success) {
        return 0
      }
      
      return (result.files || []).filter(file => !file.isDirectory).length
    } catch {
      return 0
    }
  }



  /**
   * 解析版本条目
   */
  async parseVersionEntries(versionId: string): Promise<any> {
    try {
      const versionPath = window.pathAPI.join('History', versionId)
      const result = await window.electronAPI.readDirectory(versionPath)
      
      if (!result.success) {
        throw new Error(result.error || 'Failed to read version directory')
      }
      
      const entries = (result.files || [])
        .filter(file => !file.isDirectory)
        .map(file => ({
          id: file.name,
          source: file.name,
          timestamp: file.mtime ? file.mtime.getTime() : Date.now()
        }))
      
      return {
        version: 1,
        resource: versionId,
        entries
      }
    } catch (error) {
      throw this.createError(
        ErrorType.UNKNOWN_ERROR,
        `Failed to parse version entries: ${error instanceof Error ? error.message : String(error)}`
      )
    }
  }

  /**
   * 获取文件内容
   */
  async getFileContent(versionId: string, fileId: string): Promise<string> {
    try {
      const filePath = window.pathAPI.join('History', versionId, fileId)
      const result = await window.electronAPI.readFile(filePath)
      
      if (!result.success) {
        throw new Error(result.error || 'Failed to read file')
      }
      
      return result.content || ''
    } catch (error) {
      throw this.createError(
        ErrorType.FILE_NOT_FOUND,
        `Failed to get file content: ${error instanceof Error ? error.message : String(error)}`
      )
    }
  }

  /**
   * 获取文件历史记录
   */
  async getFileHistory(filePath: string): Promise<FileHistoryRecord[]> {
    try {
      const versions = await this.scanHistoryVersions('History')
      const records: FileHistoryRecord[] = []
      
      const targetFileName = window.pathAPI.basename(filePath)
      
      for (const version of versions) {
        // 简化实现：假设文件存在于版本中
        records.push({
          versionId: version.id,
          fileId: targetFileName,
          originalPath: filePath,
          timestamp: version.timestamp,
          size: 0, // 需要实际读取文件大小
          exists: true
        })
      }
      
      return records.sort((a, b) => b.timestamp - a.timestamp)
    } catch (error) {
      throw this.createError(
        ErrorType.UNKNOWN_ERROR,
        `Failed to get file history: ${error instanceof Error ? error.message : String(error)}`
      )
    }
  }

  /**
   * 创建错误对象
   */
  private createError(type: ErrorType, message: string): AppError {
    return {
      type,
      message,
      timestamp: new Date(),
      recoverable: type !== ErrorType.UNKNOWN_ERROR
    }
  }
}

// 检查是否在 Electron 环境中
const isElectron = typeof window !== 'undefined' && window.electronAPI

// 导出适当的实例
export const historyParser = isElectron 
  ? new ElectronHistoryParserImpl()
  : null // 在非 Electron 环境中返回 null